package com.dlc.shop.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.model.AttachFileGroup;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.dao.AttachFileGroupMapper;
import com.dlc.shop.dao.AttachFileMapper;
import com.dlc.shop.service.AttachFileGroupService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author chendt
 * @date 2021/7/7 17:21
 */
@Service
@AllArgsConstructor
public class AttachFileGroupServiceImpl extends ServiceImpl<AttachFileGroupMapper, AttachFileGroup> implements AttachFileGroupService {

    private final AttachFileGroupMapper attachFileGroupMapper;
    private final AttachFileMapper attachFileMapper;

    @Override
    public List<AttachFileGroup> list(Long shopId,Integer type) {
        return attachFileGroupMapper.list(shopId, type);
    }

    @Override
    public AttachFileGroup getByAttachFileGroupId(Long attachFileGroupId) {
        return attachFileGroupMapper.getByAttachFileGroupId(attachFileGroupId);
    }

    @Override
    public void saveGroup(AttachFileGroup attachFileGroup) {
        int count = attachFileGroupMapper.getGroupCountByName(attachFileGroup.getName(), attachFileGroup.getShopId(),attachFileGroup.getType());
        if(count >= 1){
            throw new YamiShopBindException("yami.group.name.duplicate");
        }
        attachFileGroupMapper.save(attachFileGroup);
    }

    @Override
    public void update(AttachFileGroup attachFileGroup) {
        long count = attachFileGroupMapper.selectCount(Wrappers.lambdaQuery(AttachFileGroup.class)
                .eq(AttachFileGroup::getShopId, attachFileGroup.getShopId())
                .eq(AttachFileGroup::getName, attachFileGroup.getName())
                .ne(AttachFileGroup::getAttachFileGroupId, attachFileGroup.getAttachFileGroupId())
                .eq(AttachFileGroup::getType, attachFileGroup.getType())
        );
        if(count >= 1){
            throw new YamiShopBindException("yami.group.name.duplicate");
        }
        attachFileGroupMapper.update(attachFileGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long attachFileGroupId) {
        attachFileGroupMapper.deleteById(attachFileGroupId);
        attachFileMapper.updateBatchByAttachFileGroupId(attachFileGroupId);
    }
}
